﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using SmartCity.Shared;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace ParkManagement
{
    /// <summary>
    /// 停车记录应用服务类
    /// </summary>
    public class RecordAppService : ApplicationService, IRecordAppService
    {
        private readonly IRepository<Record, int> _recordRepository;

        public RecordAppService(
            IRepository<Record, int> recordRepository)
        {
            _recordRepository = recordRepository;
        }

        // 列表
        public async Task<ListResponse<RecordDto>> PagedListAsync(PagedListRequest request, string entryTime, string outTime, string parkName, string plateNumber)
        {
            // 数据筛选
            var query = await _recordRepository.WithDetailsAsync(m => m.Lot);
            query = query.WhereIf(!string.IsNullOrWhiteSpace(entryTime), m => m.EntryTime == DateTime.Parse(entryTime));
            query = query.WhereIf(!string.IsNullOrWhiteSpace(outTime), m => m.OutTime == DateTime.Parse(outTime));
            query = query.WhereIf(!string.IsNullOrWhiteSpace(parkName), m => m.Lot.ParkName.Contains(parkName));
            query = query.WhereIf(!string.IsNullOrWhiteSpace(outTime), m => m.PlateNumber == plateNumber);
            // 计数
            var count = query.Count();
            // 排序
            if (!string.IsNullOrWhiteSpace(request.OrderByColumn))
            {
                var orderColumns = request.OrderByColumn.Split(',');
                foreach (var column in orderColumns)
                {
                    query = query.OrderBy(column);
                }
            }
            // 分页
            query = query.Page(request.PageNum, request.PageSize);
            // 返回结果
            var list = await query.ToListAsync();
            var dtos = ObjectMapper.Map<List<Record>, List<RecordDto>>(list);
            return ListResponse<RecordDto>.Successful(count, dtos);
        }
    }
}